/**
 * Copyright 2016 JustWayward Team
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ecy.quadratic.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.ecy.quadratic.R;
import com.ecy.quadratic.config.ServerConfig;
import com.ecy.quadratic.reader.common.OnRvItemClickListener;
import com.ecy.quadratic.reader.utils.ScreenUtils;
import com.ecy.quadratic.widget.ComicReadCallback;
import com.yuyh.easyadapter.recyclerview.EasyRVHolder;

import java.util.HashMap;
import java.util.List;

/**
 * @author lfh.
 * @date 16/8/6.
 */
public class ComicSectionDetailAdapter extends RecyclerView.Adapter<ComicSectionDetailAdapter.ComicContentViewHolder> {
    private OnRvItemClickListener itemClickListener;
    private LayoutInflater mLayoutInflater;
    private List<String> mList;
    private Context mContext;
    private HashMap<Integer, Integer> itemHeightMap = new HashMap<>();
    private ComicReadCallback mCallback;

    public ComicSectionDetailAdapter(Context context, List<String> list, OnRvItemClickListener listener) {
        this(context, list, listener, null);
    }

    public ComicSectionDetailAdapter(Context context, List<String> list, OnRvItemClickListener listener, ComicReadCallback callback) {
        mContext = context;
        mLayoutInflater = LayoutInflater.from(context);
        this.itemClickListener = listener;
        mList = list;
        mCallback = callback;
    }

    public void clear() {
        mList.clear();
        notifyDataSetChanged();
    }


    public void addRefresh(List<String> list) {
        mList.clear();
        mList.addAll(list);
        notifyDataSetChanged();
    }

    public void addLoadMore(List<String> list) {
        mList.addAll(list);
        notifyDataSetChanged();
    }

    protected void onBindData(final EasyRVHolder holder, final int position, final String item) {
        holder.setImageUrl(R.id.pv_picture, item);
//        holder.setCircleImageUrl(R.id.ivBookCover, Constant.IMG_BASE_URL + item.author.avatar, R.drawable.avatar_default)
//                .setText(R.id.tvBookTitle, item.author.nickname)
//                .setText(R.id.tvBookType, String.format(mContext.getString(R.string
//                        .book_detail_user_lv), item.author.lv))
//                .setText(R.id.tvTitle, item.title)
//                .setText(R.id.tvContent, String.valueOf(item.content))
//                .setText(R.id.tvHelpfulYes, String.valueOf(item.helpful.yes));
//        XLHRatingBar ratingBar = holder.getView(R.id.rating);
//        ratingBar.setCountSelected(item.rating);
//        holder.setOnItemViewClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                itemClickListener.onItemClick(holder.getItemView(), position, item);
//            }
//        });
    }

    @Override
    public ComicContentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mLayoutInflater.inflate(R.layout.fragment_picture, parent, false);
        ComicContentViewHolder viewHolder = new ComicContentViewHolder(view);
        return viewHolder;

    }

    @Override
    public void onBindViewHolder(final ComicContentViewHolder holder, final int position) {

        ViewGroup.LayoutParams ivLP = holder.imageView.getLayoutParams();

        ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
        if (itemHeightMap.get(position) != null) {
            lp.height = itemHeightMap.get(position);
            ivLP.height = itemHeightMap.get(position);
        } else {
            lp.height = ScreenUtils.getScreenHeight() - ScreenUtils.dpToPxInt(120);
            ivLP.height = ScreenUtils.getScreenHeight() - ScreenUtils.dpToPxInt(120);
        }

        holder.itemView.setLayoutParams(lp);
        holder.imageView.setLayoutParams(ivLP);
//        holder.imageView.setComicBarCallback(mCallback);
        holder.imageView.setAdjustViewBounds(true);
        holder.imageView.setMaxWidth(ScreenUtils.getScreenWidth());
        holder.imageView.setMaxHeight(ScreenUtils.getScreenHeight());
        holder.mLoading.setVisibility(View.VISIBLE);
        holder.mLoading.setText(position + 1 + "");
        holder.mLoading.setVisibility(View.VISIBLE);

        System.out.println(mList.get(position));

        final RequestListener requestListener0 = new RequestListener<String, GlideDrawable>() {
            @Override
            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                String baseUrl = "";
                String footer = "";
                if (model.contains("http://mhpic.samanlehua.com")) {
                    baseUrl = "http://mhpic.zymkcdn.com";
                    footer = "-kmw.middle";
                } else if (model.contains("http://mhpic.zymkcdn.com")) {
                    baseUrl = "http://mhpic.jjmh.com";
                    footer = "";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    baseUrl = "http://mhpic.samanlehua.com";
                    footer = "";
                }
//                if(!ServerConfig.IMG_BASE_URL.equals(baseUrl)) {
                Glide.with(mContext).load(baseUrl + mList.get(position) + footer).diskCacheStrategy(DiskCacheStrategy.SOURCE).dontAnimate()
                        .into(holder.imageView);
//                }

                return false;
            }

            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                if (model.contains("http://mhpic.samanlehua.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.samanlehua.com";
                    ServerConfig.FOOTER = "-kmw.middle";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.jjmh.com";
                    ServerConfig.FOOTER = "";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.zymkcdn.com";
                    ServerConfig.FOOTER = "";
                }
                holder.mLoading.setVisibility(View.GONE);
                int height = resource.getIntrinsicHeight() * ScreenUtils.getScreenWidth() / resource.getIntrinsicWidth();
//                if(height>ScreenUtils.getScreenHeight()) {
//                    height = ScreenUtils.getScreenHeight() - ScreenUtils.dpToPxInt(120);
//                }
                if (itemHeightMap.get(position) == null || itemHeightMap.get(position) != height) {
                    itemHeightMap.put(position, height);
                    ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
                    lp.height = height;
                    holder.itemView.setLayoutParams(lp);
                    ViewGroup.LayoutParams ivLP = holder.imageView.getLayoutParams();
                    ivLP.height = height;
                    holder.imageView.setLayoutParams(ivLP);
//                    Glide.with(mContext).load(ServerConfig.IMG_BASE_URL + mList.get(position)+ServerConfig.FOOTER).fitCenter().diskCacheStrategy(DiskCacheStrategy.SOURCE).dontAnimate()
//                            .into(holder.imageView);
                }


                return false;
            }
        };

        final RequestListener requestListener = new RequestListener<String, GlideDrawable>() {
            @Override
            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                String baseUrl = "";
                String footer = "";
                if (model.contains("http://mhpic.samanlehua.com")) {
                    baseUrl = "http://mhpic.zymkcdn.com";
                    footer = "-kmw.middle";
                } else if (model.contains("http://mhpic.zymkcdn.com")) {
                    baseUrl = "http://mhpic.jjmh.com";
                    footer = "";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    baseUrl = "http://mhpic.samanlehua.com";
                    footer = "";
                }
//                if(!ServerConfig.IMG_BASE_URL.equals(baseUrl)) {
                Glide.with(mContext).load(baseUrl + mList.get(position) + footer).diskCacheStrategy(DiskCacheStrategy.SOURCE).dontAnimate()
                        .listener(requestListener0)
                        .into(holder.imageView);
//                }

                return false;
            }

            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                if (model.contains("http://mhpic.samanlehua.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.samanlehua.com";
                    ServerConfig.FOOTER = "-kmw.middle";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.jjmh.com";
                    ServerConfig.FOOTER = "";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.zymkcdn.com";
                    ServerConfig.FOOTER = "";
                }
                holder.mLoading.setVisibility(View.GONE);
                int height = resource.getIntrinsicHeight() * ScreenUtils.getScreenWidth() / resource.getIntrinsicWidth();
//                if(height>ScreenUtils.getScreenHeight()) {
//                    height = ScreenUtils.getScreenHeight() - ScreenUtils.dpToPxInt(120);
//                }
                if (itemHeightMap.get(position) == null || itemHeightMap.get(position) != height) {
                    itemHeightMap.put(position, height);
                    ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
                    lp.height = height;
                    holder.itemView.setLayoutParams(lp);
                    ViewGroup.LayoutParams ivLP = holder.imageView.getLayoutParams();
                    ivLP.height = height;
                    holder.imageView.setLayoutParams(ivLP);
//                    Glide.with(mContext).load(ServerConfig.IMG_BASE_URL + mList.get(position)+ServerConfig.FOOTER).fitCenter().diskCacheStrategy(DiskCacheStrategy.SOURCE).dontAnimate()
//                            .into(holder.imageView);
                }


                return false;
            }
        };
        final RequestListener requestListener1 = new RequestListener<String, GlideDrawable>() {
            @Override
            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                String baseUrl = "";
                String footer = "";
                if (model.contains("http://mhpic.samanlehua.com")) {
                    baseUrl = "http://mhpic.zymkcdn.com";
                    footer = "-kmw.middle";
                } else if (model.contains("http://mhpic.zymkcdn.com")) {
                    baseUrl = "http://mhpic.jjmh.com";
                    footer = "";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    baseUrl = "http://mhpic.samanlehua.com";
                    footer = "";
                }
//                if(!ServerConfig.IMG_BASE_URL.equals(baseUrl)) {
                Glide.with(mContext).load(baseUrl + mList.get(position) + footer).diskCacheStrategy(DiskCacheStrategy.SOURCE).dontAnimate()
                        .listener(requestListener)
                        .into(holder.imageView);
//                }

                return false;
            }

            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                if (model.contains("http://mhpic.samanlehua.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.samanlehua.com";
                    ServerConfig.FOOTER = "-kmw.middle";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.jjmh.com";
                    ServerConfig.FOOTER = "";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.zymkcdn.com";
                    ServerConfig.FOOTER = "";
                }
                holder.mLoading.setVisibility(View.GONE);
                int height = resource.getIntrinsicHeight() * ScreenUtils.getScreenWidth() / resource.getIntrinsicWidth();
//                if(height>ScreenUtils.getScreenHeight()) {
//                    height = ScreenUtils.getScreenHeight() - ScreenUtils.dpToPxInt(120);
//                }
                if (itemHeightMap.get(position) == null || itemHeightMap.get(position) != height) {
                    itemHeightMap.put(position, height);
                    ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
                    lp.height = height;
                    holder.itemView.setLayoutParams(lp);
                    ViewGroup.LayoutParams ivLP = holder.imageView.getLayoutParams();
                    ivLP.height = height;
                    holder.imageView.setLayoutParams(ivLP);
//                    Glide.with(mContext).load(ServerConfig.IMG_BASE_URL + mList.get(position)+ServerConfig.FOOTER).fitCenter().diskCacheStrategy(DiskCacheStrategy.SOURCE).dontAnimate()
//                            .into(holder.imageView);
                }


                return false;
            }
        };
        final RequestListener requestListener2 = new RequestListener<String, GlideDrawable>() {
            @Override
            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                String baseUrl = "";
                String footer = "";
                if (model.contains("http://mhpic.samanlehua.com")) {
                    baseUrl = "http://mhpic.zymkcdn.com";
                    footer = "-kmw.middle";
                } else if (model.contains("http://mhpic.zymkcdn.com")) {
                    baseUrl = "http://mhpic.jjmh.com";
                    footer = "";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    baseUrl = "http://mhpic.samanlehua.com";
                    footer = "";
                }
//                if(!ServerConfig.IMG_BASE_URL.equals(baseUrl)) {
                Glide.with(mContext).load(baseUrl + mList.get(position) + footer).diskCacheStrategy(DiskCacheStrategy.SOURCE).dontAnimate()
                        .listener(requestListener1)
                        .into(holder.imageView);
//                }

                return false;
            }

            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                if (model.contains("http://mhpic.samanlehua.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.samanlehua.com";
                    ServerConfig.FOOTER = "-kmw.middle";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.jjmh.com";
                    ServerConfig.FOOTER = "";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.zymkcdn.com";
                    ServerConfig.FOOTER = "";
                }
                holder.mLoading.setVisibility(View.GONE);
                int height = resource.getIntrinsicHeight() * ScreenUtils.getScreenWidth() / resource.getIntrinsicWidth();
//                if(height>ScreenUtils.getScreenHeight()) {
//                    height = ScreenUtils.getScreenHeight() - ScreenUtils.dpToPxInt(120);
//                }
                if (itemHeightMap.get(position) == null || itemHeightMap.get(position) != height) {
                    itemHeightMap.put(position, height);
                    ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
                    lp.height = height;
                    holder.itemView.setLayoutParams(lp);
                    ViewGroup.LayoutParams ivLP = holder.imageView.getLayoutParams();
                    ivLP.height = height;
                    holder.imageView.setLayoutParams(ivLP);
//                    Glide.with(mContext).load(ServerConfig.IMG_BASE_URL + mList.get(position)+ServerConfig.FOOTER).fitCenter().diskCacheStrategy(DiskCacheStrategy.SOURCE).dontAnimate()
//                            .into(holder.imageView);
                }


                return false;
            }
        };

        final RequestListener requestListener3 = new RequestListener<String, GlideDrawable>() {
            @Override
            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                String baseUrl = "";
                String footer = "";
                if (model.contains("http://mhpic.samanlehua.com")) {
                    baseUrl = "http://mhpic.zymkcdn.com";
                    footer = "-kmw.middle";
                } else if (model.contains("http://mhpic.zymkcdn.com")) {
                    baseUrl = "http://mhpic.jjmh.com";
                    footer = "";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    baseUrl = "http://mhpic.samanlehua.com";
                    footer = "";
                }
//                if(!ServerConfig.IMG_BASE_URL.equals(baseUrl)) {
                Glide.with(mContext).load(baseUrl + mList.get(position) + footer).diskCacheStrategy(DiskCacheStrategy.SOURCE).dontAnimate()
                        .listener(requestListener2)
                        .into(holder.imageView);
//                }

                return false;
            }

            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                if (model.contains("http://mhpic.samanlehua.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.samanlehua.com";
                    ServerConfig.FOOTER = "-kmw.middle";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.jjmh.com";
                    ServerConfig.FOOTER = "";
                } else if (model.contains("http://mhpic.jjmh.com")) {
                    ServerConfig.IMG_BASE_URL = "http://mhpic.zymkcdn.com";
                    ServerConfig.FOOTER = "";
                }
                holder.mLoading.setVisibility(View.GONE);
                int height = resource.getIntrinsicHeight() * ScreenUtils.getScreenWidth() / resource.getIntrinsicWidth();
//                if(height>ScreenUtils.getScreenHeight()) {
//                    height = ScreenUtils.getScreenHeight() - ScreenUtils.dpToPxInt(120);
//                }
                if (itemHeightMap.get(position) == null || itemHeightMap.get(position) != height) {
                    itemHeightMap.put(position, height);
                    ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
                    lp.height = height;
                    holder.itemView.setLayoutParams(lp);
                    ViewGroup.LayoutParams ivLP = holder.imageView.getLayoutParams();
                    ivLP.height = height;
                    holder.imageView.setLayoutParams(ivLP);
//                    Glide.with(mContext).load(ServerConfig.IMG_BASE_URL + mList.get(position)+ServerConfig.FOOTER).fitCenter().diskCacheStrategy(DiskCacheStrategy.SOURCE).dontAnimate()
//                            .into(holder.imageView);
                }


                return false;
            }
        };

        Glide.with(mContext).load(ServerConfig.IMG_BASE_URL + mList.get(position) + ServerConfig.FOOTER).diskCacheStrategy(DiskCacheStrategy.SOURCE).dontAnimate()
                .listener(requestListener3)
                .into(holder.imageView);

        if ((position + 1) < getItemCount()) {
            Glide.with(mContext).load(ServerConfig.IMG_BASE_URL + mList.get(position + 1) + ServerConfig.FOOTER).diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .preload();
            if ((position + 2) < getItemCount()) {
                Glide.with(mContext).load(ServerConfig.IMG_BASE_URL + mList.get(position + 2) + ServerConfig.FOOTER).diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .preload();
            }
            if ((position + 3) < getItemCount()) {
                Glide.with(mContext).load(ServerConfig.IMG_BASE_URL + mList.get(position + 3) + ServerConfig.FOOTER).diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .preload();
            }
            if ((position + 4) < getItemCount()) {
                Glide.with(mContext).load(ServerConfig.IMG_BASE_URL + mList.get(position + 4) + ServerConfig.FOOTER).diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .preload();
            }
            if ((position + 5) < getItemCount()) {
                Glide.with(mContext).load(ServerConfig.IMG_BASE_URL + mList.get(position + 5) + ServerConfig.FOOTER).diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .preload();
            }
        }
    }

    @Override
    public int getItemCount() {
        return mList == null ? 0 : mList.size();
    }

    public static class ComicContentViewHolder extends RecyclerView.ViewHolder {

        public ImageView imageView;
        public TextView mLoading;

        public ComicContentViewHolder(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.pv_picture);

            mLoading = (TextView) itemView.findViewById(R.id.loading);
        }
    }
}